package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.exceptions.BusinessException;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import cn.kgc.vue.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/9/25
 * @description
 */
@RestController
@RequestMapping("role")
@Slf4j
@Tag(name = "角色模块")
public class RoleController {

    @Resource
    private RoleService roleService;

    // 添加角色权限  addPermissions
    @PostMapping("addPermissions")
    @Operation(summary = "添加角色权限")
    public ResponseResult addPermissions(@RequestBody Map<String,Object> params){
        log.error("params={}",params);
        return roleService.addPermissions(params);
    }

    // 获取角色权限
    @GetMapping("permission/{id}")
    @Operation(summary = "获取角色权限")
    @Parameters({
            @Parameter(name = "id",description = "角色id",required = true),
    })
    public ResponseResult rolePermissions(@PathVariable("id") Integer id){

       return roleService.rolePermissions(id);

    }

    // 角色列表  下拉选
    @GetMapping("list")
    @Operation(summary = "角色列表")
    public ResponseResult  roleList(){
        List<Role> list = roleService.list();
        return  ResponseResult.success()
                .data("roleList",list);
    }

    @PostMapping("page")
    @Operation(summary = "角色分页")
    public ResponseResult  rolePage(@RequestBody QueryCondition<Role> queryCondition){
       return   roleService.rolePage(queryCondition);
    }


    @PutMapping("addOrEdit")
    @Operation(summary = "添加/编辑角色")
    public ResponseResult addOrEdit(@RequestBody Role role){

        try {
            roleService.saveOrUpdate(role);
        }catch (DuplicateKeyException e){
            throw  new BusinessException(ResponseStatus.ERROR.getCode(),"角色名或角色标识重复,请检查...");
        }

        return ResponseResult.success();
    }


    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除角色")
    public ResponseResult removeRole(@PathVariable("id") Integer id){

       return roleService.removeRole(id);
    }
}
